import $ from './library/jquery.js';
import cookie from './library/cookie.js';

// 通过search获取商品id
let id=location.search.split('=')[1];

function addItem(id, price, num) {
    let shop = cookie.get('shop');

    let product = {
        id,
        price,
        num
    }

    // 判断当前cookie中是否有购物数据
    if (shop) { // 如果有数据 取出是一个字符串
        shop = JSON.parse(shop);

        // 添加之前先要判断数据中有没有该商品
        if (shop.some(el => el.id === id)) {
            let _index = shop.findIndex(elm => elm.id == id);
            let count = parseInt(shop[_index].num);
            count += parseInt(num);
            shop[_index].num = count;
        } else {
            shop.push(product);
        }


    } else { // 第一次没有数据的情况 创建一个新数据
        shop = [];
        shop.push(product);
    }

    cookie.set('shop', JSON.stringify(shop), 1);
}

$.ajax({
    type:"get",
    url:"../interface/getItem.php",
    data:{
        id:id
    },
    dataType:"json",
    success: function(res){
        let picture=JSON.parse(res.picture);

        let tu=`<img src="./${picture[1].src}" alt="">`;
        let h=`<h2>${res.title}</h2>`;
        let name_price_sum=`<p class="name">20W高速无线充套装白色<span class="price">${res.price}元</span></p>
        <p class="sum">总计:${res.price}元</p>`;

        $('.content>.tu').append(tu);
        $('.content>.zi').prepend(h);
        $('.jiesuan').append(name_price_sum);

        $('.add_shopcar').on('click', function() {
            addItem(res.id, res.price, 1);
        });
    }
    


});

// nav 下拉菜单
let xiala=$("#xiala>li");
let caidan=$(".menu_n");

$('.nav').on('mouseenter','#xiala>li',function(){
    let index=$(this).index();
    
    let timer=setTimeout(function(){
        $('.menu_nav').show();
        caidan.eq(-index+8).slideDown(200,"linear");
        xiala.on('mouseenter',function(){
            let index=$(this).index();
            let index2=-index+8;
            caidan.eq(index2).show().siblings().hide();
        });
    }, 200);
    
    $('.nav').on('mouseleave',function(){
        clearTimeout(timer);
        caidan.slideUp(200,"linear");
        $('.menu_nav').hide();
    });
});